import 'dart:developer';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sports_new/controller/live/ali_live_logic.dart';
import 'package:sports_new/controller/live/qkd_player_logic.dart';
import 'package:sports_new/controller/match/detail/zq_match_detail_logic.dart';
import 'package:sports_new/entity/match/match_live_entity.dart';
import 'package:sports_new/entity/match/zq_match_info_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/match_detail/live/live_source_sheet.dart';
import 'package:sports_new/widgets/circular.dart';
import 'package:sports_new/widgets/count_down_text.dart';
import 'package:url_launcher/url_launcher_string.dart';
import '../../../controller/live/live_chat_logic.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/gif.dart';

class ZqDetailHeaderWidget extends StatelessWidget {
  ZqDetailHeaderWidget({
    super.key,
    this.info,
    required this.logic,
    // this.liveAnimation = false,
    // this.animatelivePress
  });

  ZqMatchInfoEntity? info;
  // List<MatchVideoEntity>? videoList;
  // FutureOr Function()? animatelivePress;

  // bool liveAnimation;
  final ZqMatchDetailLogic logic;

  @override
  Widget build(BuildContext context) {
    return _header(context);
  }

  Widget _header(BuildContext context) {
    var details = <String>[];
    if (info?.halfScoreRate != null) {
      if (info?.state == MatchState.notStart) {
      } else {
        details.add("半场${info?.halfScoreRate}");
      }
    }
    if (info?.otScoreRate != null) {
      details.add("加时${info?.otScoreRate}");
    }
    if (info?.pkScoreRate != null) {
      details.add("点球${info?.pkScoreRate}");
    }
    final detailTexts = <Widget>[];
    for (var i = 0; i < details.length; i += 1) {
      if (i + 1 < details.length && i != 0) {
        detailTexts.add(QkdText(
          "${details[i]} ${details[i + 1]}",
        ));
        i += 1;
      } else {
        detailTexts.add(QkdText(details[i]));
      }
    }
    bool hasVideo =
        logic.roomList?.any((element) => element.vtype != 4) ?? false;
    bool onLive = logic.roomList?.any((element) =>
            element.roomId != 0 &&
            element.playStatus == 1 &&
            element.vtype != 4) ??
        false;
    bool hasAnimation =
        logic.roomList?.any((element) => element.vtype == 4) ?? false;
    final content = Container(
        // height: 140,
        padding: EdgeInsets.only(
            top: kToolbarHeight + MediaQuery.of(context).padding.top),
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage(Utils.getImgPath('zq_detail_header.png')),
                fit: BoxFit.fitWidth)),
        // color: Colours.blue2766D6,
        child: Row(
          children: [
            Expanded(
                child: _teamCol(
                    info?.baseInfo?.homeLogo ?? "",
                    info?.baseInfo?.homeNameAll ?? "",
                    info?.baseInfo?.homeRanking,
                    info?.baseInfo?.homeId ?? 0,
                    2)),
            Column(
              children: [
                const SizedBox(height: 20),
                (info?.state == MatchState.notStart)
                    ? Container(height: 15)
                    : Container(
                        height: 20,
                        width: 42,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: Colours.white25),
                        child: info?.state == MatchState.inMatch
                            ? info?.runningTime != null
                                ? Wrap(
                                    children: [
                                      QkdText(
                                          info?.runningTime
                                                  ?.replaceAll("'", "") ??
                                              "",
                                          color: Colors.white,
                                          fontSize: 12),
                                      const QkdText("'",
                                              color: Colors.white, fontSize: 12)
                                          .animate(
                                              onPlay: (controller) =>
                                                  controller.repeat())
                                          .fade(duration: 1000.ms)
                                    ],
                                  )
                                : QkdText(info?.baseInfo?.statusName ?? "",
                                    fontSize: 13)
                            : QkdText(info?.baseInfo?.statusName ?? "",
                                fontSize: 13),
                      ),
                const SizedBox(height: 6),
                if (info?.state == MatchState.notStart &&
                    (info?.baseInfo?.matchTime.time
                                ?.difference(DateTime.now())
                                .inHours ??
                            0) <=
                        24 &&
                    (info?.baseInfo?.matchTime.time
                                ?.difference(DateTime.now())
                                .inHours ??
                            0) >
                        0) ...[
                  CountDownText.toStart(
                    startTime: info!.baseInfo!.matchTime!,
                    textStyle: const TextStyle(
                        fontSize: 22,
                        fontFamily: "Din",
                        fontWeight: FontWeight.w500),
                  ),
                  const QkdText("距比赛开始", fontSize: 12, color: Colours.white)
                ] else
                  QkdText(
                    info?.centerTitle ?? "",
                    fontSize: 22,
                    fontFamily: 'DIN',
                    maxLines: 1,
                  ),
                const SizedBox(height: 6),
                DefaultTextStyle(
                  style: const TextStyle(fontSize: 12, height: 1.5),
                  maxLines: 1,
                  child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: detailTexts),
                ),
                const Spacer(),
                if (logic.roomList.hasValue)
                  Circular(
                      radius: 10,
                      color: Colours.black.withOpacity(0.15),
                      height: 20,
                      padding: const EdgeInsets.symmetric(horizontal: 8),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          if (hasVideo)
                            GestureDetector(
                              onTap: () => onTapLive(),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  if (onLive)
                                    const GifWidget(
                                        width: 14,
                                        height: 14,
                                        asset: "in_live.gif",
                                        duration: Duration(milliseconds: 500))
                                  else
                                    Image.asset(
                                      Utils.getImgPath("live_video_border.png"),
                                      width: 14,
                                    ),
                                  const SizedBox(width: 2),
                                  const QkdText("视频直播",
                                      fontSize: 12, color: Colours.white)
                                ],
                              ),
                            ),
                          if (hasVideo && hasAnimation)
                            const QkdText("  |  ",
                                fontSize: 12, color: Colours.white),
                          if (hasAnimation)
                            GestureDetector(
                              onTap: () => onTapLive(false),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Image.asset(
                                    Utils.getImgPath(
                                        "live_animation_border.png"),
                                    width: 14,
                                  ),
                                  const SizedBox(width: 2),
                                  const QkdText("动画直播",
                                      fontSize: 12, color: Colours.white)
                                ],
                              ),
                            )
                        ],
                      )),
                const SizedBox(height: 15)
              ],
            ).sized(width: 162),
            Expanded(
                child: _teamCol(
                    info?.baseInfo?.guestLogo ?? "",
                    info?.baseInfo?.guestNameAll ?? "",
                    info?.baseInfo?.guestRanking,
                    info?.baseInfo?.guestId ?? 0,
                    3)),
          ],
        ));
    return DefaultTextStyle(
        style: const TextStyle(color: Colors.white, fontSize: 14),
        child: content);
  }

  _teamCol(String logo, String name, String? rank, int id, int type) {
    return GestureDetector(
      onTap: () {
        Utils.onEvent('bsxq', params: {"bsxq": type});
        Get.toNamed(Routes.zqTeamDetail, arguments: id);
      },
      child: Column(
        children: [
          const SizedBox(height: 25),
          logo.length == 0 && info == null
              ? Styles.placeholderIcon(width: 54, height: 54)
              : CachedNetworkImage(
                  imageUrl: logo,
                  // width: 50,
                  height: 50,
                  fit: BoxFit.cover,
                  placeholder: (context, url) =>
                      Styles.placeholderIcon(width: 50),
                  errorWidget: (context, url, error) => Image.asset(
                    Utils.getImgPath("zq_placeholder.png"),
                    fit: BoxFit.cover,
                  ),
                ),
          const SizedBox(height: 5),
          QkdText(name, maxLines: 1, fontWeight: FontWeight.w500),
          QkdText(rank?.isEmpty ?? true ? "" : "[${rank ?? ""}]",
              fontSize: 11, color: Colours.white.withOpacity(0.6))
        ],
      ),
    );
  }

  onTapLive([bool isLive = true]) async {
    Utils.onEvent('bsxq_dhzb');
    if (logic.roomList.noValue) {
      await logic.getVideo();
    }
    if (logic.roomList.hasValue) {
      int? index;
      if (isLive) {
        index = await LiveSourceSheet.show(
            liveList: logic.roomList
                    ?.where((element) => element.vtype != 4)
                    .toList() ??
                [],
            select: logic.liveInfo?.expertId);
      } else {
        index = logic.roomList?.indexWhere((element) => element.vtype == 4);
      }
      if (index != null) {
        MatchLiveEntity live = logic.roomList![index];
        if (isLive && !live.playStatus.hasValue) {
          ToastUtils.show("暂未开始直播，请耐心等待");
          Utils.onEvent("match_detail_live_view",
              params: {"is_on": 0, "id": live.roomId});
          return;
        } else if (live.roomId == 0) {
          Utils.onEvent("match_detail_stream_view");
        }
        if (live.vformat == 'URL') {
          launchUrlString(live.url ?? '',
              mode: LaunchMode.externalApplication,
              webViewConfiguration:
                  const WebViewConfiguration(enableDomStorage: false));
        } else {
          if (live.copyright == 0) {
            Utils.onEvent("match_detail_live_view",
                params: {"is_on": 1, "id": live.roomId});
            logic.setLiveStream(true, roomInfo: live);
            try {
              LiveChatLogic chatLogic =
                  Get.find<LiveChatLogic>(tag: "${live.matchId}");
              chatLogic.getRefresh();
            } catch (e) {
              log("");
            }
            try {
              QkdPlayerLogic playerLogic =
                  Get.find<QkdPlayerLogic>(tag: "${live.matchId}");
              playerLogic.url = live.url ?? "";
              playerLogic.doRefresh();
            } catch (e) {
              log("");
            }
          } else {
            ToastUtils.show('暂无版权，请选择其他直播源');
          }
        }
      }
    }
  }
}
